const { net } = require("electron").remote;
import { message } from "ant-design-vue";
import { dataEncrypt, dataDecrypt } from './wholeEncrypt'
import config from '../config'
import { dataType } from './index'
export default {
  send(sendObj) {
    return new Promise((resolve, reject) => {
      const headers = {
        "Content-Type":"application/json;charset=utf-8",
        'token': JSON.parse(localStorage.getItem('state')) ? JSON.parse(localStorage.getItem('state')).token : ''
      };
      let rowData = "";
      let request = net.request({
        method: sendObj.method,
        url: `${config.prod_Api}${sendObj.path}`,
        headers: sendObj.headers || headers,
      });
      request.on("response", (response) => {
        //监听响应
        // console.log(response.statusCode); //返回状态码
        // console.log(response.headers);  //返回请求头
        // 监听结束
        response.on("end", () => {
          let res =(JSON.parse(rowData) && JSON.parse(rowData).cipherText && config.isEncry) ? JSON.parse(dataDecrypt(JSON.parse(rowData))) : JSON.parse(rowData)
          if(response.statusCode === 200 || res.code == 200){
            if (res.code === "200") {
                resolve(res);
              } else if (res.code === "403") {
                message.error("token已失效，请重新登录！");
              } else {
                if(res.code === "8004"){
                  message.error(res.message);
                }else{
                  message.error(res.message);
                }
                reject(res);
              }
          }else{
            message.error('网络连接失败！');
            reject('网络连接失败！')
          }
        });
        response.on("data", (chunk) => {
          //获取返回数据
          rowData += chunk.toString();
        });
      });
      // 通过 request.write() 方法，发送的 post 请求数据需要先进行序列化，变成纯文本的形式
      let data = (dataType(sendObj.postData) !== 'formdata') && config.isEncry ? {
        params: {
          cipherText: dataEncrypt(JSON.stringify(sendObj.postData || {})),
        },
      } : (sendObj.postData || {});
      request.write(JSON.stringify(data));
      request.end(); //结束请求,不结束无法返回数据
    });
  },
};
